<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-material.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"blog.yookingh.cn","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":true,"color":"#00000000","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="发现Calendar的比较时基于毫秒的，但是calendar使用set方法只能精确到秒，如果用Calendar进行同一秒的比较，可能会有…">
<meta property="og:type" content="article">
<meta property="og:title" content="Calendar的时间比对问题">
<meta property="og:url" content="http://blog.yookingh.cn/dev/200731-CalendarComparative.html">
<meta property="og:site_name" content="墨染青葱几许烟">
<meta property="og:description" content="发现Calendar的比较时基于毫秒的，但是calendar使用set方法只能精确到秒，如果用Calendar进行同一秒的比较，可能会有…">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-07-31T00:41:00.000Z">
<meta property="article:modified_time" content="2020-07-31T02:57:40.976Z">
<meta property="article:author" content="yooking">
<meta property="article:tag" content="学习笔记">
<meta property="article:tag" content="Android">
<meta property="article:tag" content="Java">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://blog.yookingh.cn/dev/200731-CalendarComparative.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Calendar的时间比对问题 | 墨染青葱几许烟</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">墨染青葱几许烟</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">左手代码 右手诗意</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-首页">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-时间轴">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>时间轴</a>

  </li>
        <li class="menu-item menu-item-标签云">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签云</a>

  </li>
        <li class="menu-item menu-item-关于&留言">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于&留言</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <a href="https://github.com/yooking-git" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://blog.yookingh.cn/dev/200731-CalendarComparative.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/imgs/a_icon_head.jpg">
      <meta itemprop="name" content="yooking">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="墨染青葱几许烟">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Calendar的时间比对问题
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-07-31 08:41:00" itemprop="dateCreated datePublished" datetime="2020-07-31T08:41:00+08:00">2020-07-31</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dev/" itemprop="url" rel="index"><span itemprop="name">想丶给代码码上诗意</span></a>
                </span>
            </span>

          
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/dev/200731-CalendarComparative.html#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/dev/200731-CalendarComparative.html" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="发现"><a href="#发现" class="headerlink" title="发现"></a>发现</h1><p>Calendar的比较时基于毫秒的，但是calendar使用set方法只能精确到秒，如果用Calendar进行同一秒的比较，可能会有…<a id="more"></a></p>
<p>会有如下代码：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MainActivity</span> <span class="keyword">extends</span> <span class="title">AppCompatActivity</span></span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">final</span> String TAG = <span class="string">"MainActivity"</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>.onCreate(savedInstanceState);</span><br><span class="line">        setContentView(R.layout.activity_main);</span><br><span class="line">        </span><br><span class="line">        Calendar calStart = Calendar.getInstance();</span><br><span class="line">        calStart.set(<span class="number">2008</span>,<span class="number">0</span>,<span class="number">1</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>);<span class="comment">//2008.01.01 00:00:00</span></span><br><span class="line">        </span><br><span class="line">        setOnClickListener(v-&gt;&#123;</span><br><span class="line">            Calendar calEnd = Calendar.getInstance();</span><br><span class="line">            calEnd.set(<span class="number">2008</span>,<span class="number">0</span>,<span class="number">1</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>);<span class="comment">//2008.01.01 00:00:00</span></span><br><span class="line">            Log.i(TAG,<span class="string">"is startTime before endTime?"</span>+isNotBefore(calStart,calEnd));</span><br><span class="line">        &#125;,R.id.tv_main_comparative)</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">isNotBefore</span><span class="params">(Calendar calStart,Calendar calEnd)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> !calStart.before(calEnd);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">setOnClickListener</span><span class="params">(OnClickListener listener,@ResId <span class="keyword">int</span> ... ids)</span></span>&#123;</span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> id:ids)&#123;</span><br><span class="line">            findViewById(id).setOnClickListener(listener)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//日志结果</span></span><br><span class="line"><span class="comment">//首次点击：MainActivity:is startTime before endTime?false</span></span><br><span class="line"><span class="comment">//再次点击：MainActivity:is startTime before endTime?true</span></span><br><span class="line"><span class="comment">//多次点击：...或false或true</span></span><br></pre></td></tr></table></figure>

<p>每次点击时的结果都是不尽相同的。为什么？</p>
<h1 id="探索"><a href="#探索" class="headerlink" title="探索"></a>探索</h1><p>我们尝试新增如下日志</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">onCreate</span><span class="params">(Bundle savedInstanceState)</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    setOnClickListener(v-&gt;&#123;</span><br><span class="line">        ...</span><br><span class="line">        Log.i(TAG,<span class="string">"startTime.getTimeInMillis():"</span>+calStart.getTimeInMillis()+<span class="string">"---&gt;endTime.getTimeInMillis():"</span>+calEnd.getTimeInMillis());</span><br><span class="line">    &#125;,R.id.tv_main_comparative);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到打出的日志（这里就不贴日志了，可以自行尝试）有毫秒级的差别，也就是：</p>
<ol>
<li>calStart的真实时间是2008.01.01 00:00:00.xxx<br>（注：xxx是<code>Calendar calStart = Calendar.getInstance();</code>时的毫秒数）</li>
<li>calEnd的真实时间的毫秒数则是点击瞬间的毫秒数</li>
<li>由于毫秒数的不确定性，导致时而calStart大于、时而小于、时而等于calEnd</li>
</ol>
<h1 id="解决方案"><a href="#解决方案" class="headerlink" title="解决方案"></a>解决方案</h1><p>解决方案有两种：</p>
<ol>
<li><p>在使用到Calendar的类中定义一个基础Calendar</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">Calendar calBase = Calendar.getInstance();</span><br><span class="line"></span><br><span class="line">Calendar calStart = Calendar.getInstance();</span><br><span class="line">calStart.setTime(calBase.getTime());</span><br><span class="line">calStart.set(<span class="number">2008</span>,<span class="number">0</span>,<span class="number">1</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">Calendar calEnd = Calendar.getInstance();</span><br><span class="line">calEnd.setTime(calBase.getTime());</span><br><span class="line">calEnd.set(<span class="number">2008</span>,<span class="number">0</span>,<span class="number">1</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>);</span><br></pre></td></tr></table></figure>

<p>千万别写成如下：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//那我还得和你解释数据是怎么存储在堆和栈中... pass</span></span><br><span class="line">Calendar calStart = calBase;</span><br><span class="line">calStart.set(<span class="number">2008</span>,<span class="number">0</span>,<span class="number">1</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">Calendar calEnd = calBase;</span><br><span class="line">calStart.set(<span class="number">2008</span>,<span class="number">0</span>,<span class="number">1</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>);</span><br></pre></td></tr></table></figure>

<p>这种写法其实都是在操作calBase，都不能算是另外操作calStart和calEnd.可尝试如下代码看看效果：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">initTry</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    Calendar calBase = Calendar.getInstance();</span><br><span class="line">    Calendar calStart = calBase;</span><br><span class="line">    calBase.set(<span class="number">2008</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>);</span><br><span class="line">    Calendar calEnd = calBase;</span><br><span class="line">    calEnd.set(<span class="number">2009</span>,<span class="number">1</span>,<span class="number">1</span>,<span class="number">0</span>,<span class="number">0</span>,<span class="number">0</span>);</span><br><span class="line">    Log.i(TAG,<span class="string">"log\nCalendar0--&gt;"</span>+calStart.getTime().toString()+<span class="string">"\nCalendar1--&gt;"</span>+calEnd.getTime().toString());</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//日志</span></span><br><span class="line"><span class="comment">//log</span></span><br><span class="line"><span class="comment">//    Calendar0--&gt;Sun Feb 01 00:00:00 GMT+08:00 2009</span></span><br><span class="line"><span class="comment">//    Calendar1--&gt;Sun Feb 01 00:00:00 GMT+08:00 2009</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>比较时根据精确度进行比较：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CalendarUtils</span></span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">isNotBefore</span><span class="params">(Calendar calStart, Calendar calEnd, @NotNull CalendarType type)</span> </span>&#123;</span><br><span class="line"><span class="comment">//        int startYear = calStart.get(Calendar.YEAR);</span></span><br><span class="line"><span class="comment">//        int endYear = calEnd.get(Calendar.YEAR);</span></span><br><span class="line"><span class="comment">//        if (startYear &lt;= endYear) return false;</span></span><br><span class="line">        <span class="keyword">if</span> (ifBefore(calStart,calEnd,Calendar.YEAR)) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (CalendarType.YEAR == type) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//        int startMonth = calStart.get(Calendar.MONTH);</span></span><br><span class="line"><span class="comment">//        int endMonth = calEnd.get(Calendar.MONTH);</span></span><br><span class="line"><span class="comment">//        if (startMonth &lt;= endMonth) return false;</span></span><br><span class="line">        <span class="keyword">if</span> (ifBefore(calStart,calEnd,Calendar.MONTH)) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (CalendarType.MONTH == type) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//        int startDay = calStart.get(Calendar.DAY_OF_MONTH);</span></span><br><span class="line"><span class="comment">//        int endDay = calEnd.get(Calendar.DAY_OF_MONTH);</span></span><br><span class="line"><span class="comment">//        if (startDay &lt;= endDay) return false;</span></span><br><span class="line">        <span class="keyword">if</span> (ifBefore(calStart,calEnd,Calendar.DAY_OF_MONTH)) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (CalendarType.DAY == type) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//        int startHour = calStart.get(Calendar.HOUR_OF_DAY);</span></span><br><span class="line"><span class="comment">//        int endHour = calEnd.get(Calendar.HOUR_OF_DAY);</span></span><br><span class="line"><span class="comment">//        if (startHour &lt;= endHour) return false;</span></span><br><span class="line">        <span class="keyword">if</span> (ifBefore(calStart,calEnd,Calendar.HOUR_OF_DAY)) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (CalendarType.HOUR == type) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//        int startMinute = calStart.get(Calendar.MINUTE);</span></span><br><span class="line"><span class="comment">//        int endMinute = calEnd.get(Calendar.MINUTE);</span></span><br><span class="line"><span class="comment">//        if (startMinute &lt;= endMinute) return false;</span></span><br><span class="line">        <span class="keyword">if</span> (ifBefore(calStart,calEnd,Calendar.MINUTE)) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (CalendarType.MINUTE == type) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//        int startSecond = calStart.get(Calendar.SECOND);</span></span><br><span class="line"><span class="comment">//        int endSecond = calEnd.get(Calendar.SECOND);</span></span><br><span class="line"><span class="comment">//        if (startSecond &lt;= endSecond) return false;</span></span><br><span class="line">        <span class="keyword">if</span> (ifBefore(calStart,calEnd,Calendar.SECOND)) <span class="keyword">return</span> <span class="keyword">false</span>;</span><br><span class="line">        <span class="keyword">if</span> (CalendarType.SECOND == type) <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> calStart.getTimeInMillis() &gt;= calEnd.getTimeInMillis();</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//后续做了变更，封装此方法，方便调整代码</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">boolean</span> <span class="title">isBefore</span><span class="params">(Calendar calStart,Calendar calEnd,<span class="keyword">int</span> calendarField)</span></span>&#123;</span><br><span class="line">        <span class="keyword">return</span> calStart.get(calendarField)&lt;=calEnd.get(calendarField);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">enum</span> CalendarType &#123;</span><br><span class="line">        YEAR, MONTH, DAY, HOUR, MINUTE, SECOND, MILLIS_SECOND</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<h1 id="结语"><a href="#结语" class="headerlink" title="结语"></a>结语</h1><p><strong>写代码时务必要注重细节~</strong></p>
<p>另：<del>（免责声明）</del>以上代码未在编辑器上校验过，纯手打~</p>
<p>如有问题，请根据实际情况修改代码</p>
<p>如有疑问，评论区见~</p>

    </div>

    
    
    
        <div class="reward-container">
  <div><font color="#FF0000">------------本文结束<i class="fa fa-paw"></i>感谢您的阅读------------</font><br/><br/>Thank you for your accept！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/imgs/a_icon_pay_wechat.png" alt="yooking 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/imgs/a_icon_pay_ali.png" alt="yooking 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>

	  

      <footer class="post-footer">
		<div>
			
				
<div class="my_post_copyright">
  <script src="//cdn.bootcss.com/clipboard.js/1.5.10/clipboard.min.js"></script>
  
  <!-- JS库 sweetalert 可修改路径 -->
  <script type="text/javascript" src="http://jslibs.wuxubj.cn/sweetalert_mini/jquery-1.7.1.min.js"></script>
  <script src="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.min.js"></script>
  <link rel="stylesheet" type="text/css" href="http://jslibs.wuxubj.cn/sweetalert_mini/sweetalert.mini.css">

  <p><span>本文标题:</span>Calendar的时间比对问题</a></p>
  <p><span>文章作者:</span>yooking</a></p>
  <p><span>发布时间:</span>2020年07月31日 - 08:41:00</p>
  <p><span>最后更新:</span>2020年07月31日 - 10:57:40</p>
  <p><span>原始链接:</span><a href="/dev/200731-CalendarComparative.html" title="Calendar的时间比对问题">http://blog.yookingh.cn/dev/200731-CalendarComparative.html</a>
    <span class="copy-path"  title="点击复制文章链接"><i class="fa fa-clipboard" data-clipboard-text="http://blog.yookingh.cn/dev/200731-CalendarComparative.html"  aria-label="复制成功！"></i></span>
  </p>
  <p><span>许可协议:</span>© <a rel="license" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
</div>
<script> 
    var clipboard = new Clipboard('.fa-clipboard');
    clipboard.on('success', $(function(){
      $(".fa-clipboard").click(function(){
        swal({   
          title: "",   
          text: '复制成功',   
          html: false,
          timer: 500,   
          showConfirmButton: false
        });
      });
    }));  
</script>

			
		</div>
          
          <div class="post-tags">
              <a href="/tags/study/" rel="tag"><i class="fa fa-tag"></i> 学习笔记</a>
              <a href="/tags/Android/" rel="tag"><i class="fa fa-tag"></i> Android</a>
              <a href="/tags/Java/" rel="tag"><i class="fa fa-tag"></i> Java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/dev/200709-ScanQRCode.html" rel="prev" title="自定义二维码扫描">
      <i class="fa fa-chevron-left"></i> 自定义二维码扫描
    </a></div>
      <div class="post-nav-item">
    <a href="/dev/200806-playAndroid.html" rel="next" title="玩Android_APP开发进度及项目介绍">
      玩Android_APP开发进度及项目介绍 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">
      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#发现"><span class="nav-number">1.</span> <span class="nav-text">发现</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#探索"><span class="nav-number">2.</span> <span class="nav-text">探索</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#解决方案"><span class="nav-number">3.</span> <span class="nav-text">解决方案</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#结语"><span class="nav-number">4.</span> <span class="nav-text">结语</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="yooking"
      src="/imgs/a_icon_head.jpg">
  <p class="site-author-name" itemprop="name">yooking</p>
  <div class="site-description" itemprop="description"></div>
</div>

<div id="music_163">
	<iframe frameborder="no" border="0" marginwidth="0" marginheight="0" height=86 src="//music.163.com/outchain/player?type=2&id=1417959188&auto=1&height=66"></iframe>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives">
          <span class="site-state-item-count">23</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
        <span class="site-state-item-count">3</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/yooking-git" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;yooking-git" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:android_yoo@126.com" title="E-Mail → mailto:android_yoo@126.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="https://www.chensheng.group/" title="https:&#x2F;&#x2F;www.chensheng.group&#x2F;" rel="noopener" target="_blank">陈先生的小前端</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://github.com/theme-next" title="https:&#x2F;&#x2F;github.com&#x2F;theme-next" rel="noopener" target="_blank">NexT主题Github</a>
        </li>
        <li class="links-of-blogroll-item">
          <a href="https://hexo-theme-next.netlify.app/" title="https:&#x2F;&#x2F;hexo-theme-next.netlify.app&#x2F;" rel="noopener" target="_blank">NexT主题博客</a>
        </li>
    </ul>
  </div>

      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 2019 – 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">yooking</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">118k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">1:47</span>
</div>
<div>
<span id="timeDate">载入天数...</span><span id="times">载入时分秒...</span>
<script>
    var now = new Date();
    function createtime() {
        var grt= new Date("04/07/2019 00:00:00");
        now.setTime(now.getTime()+250);
        days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days);
        hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours);
        if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
        mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;}
        seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
        snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;}
        document.getElementById("timeDate").innerHTML = "本站已安全运行 "+dnum+" 天 ";
        document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒";
    }
setInterval("createtime()",250);
</script>
</div>


  <script src='https://unpkg.com/mermaid@7.1.2/dist/mermaid.min.js'></script>
  <script>
    if (window.mermaid) {
      mermaid.initialize({theme: 'forest'});
    }
  </script>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script color='0,0,0' opacity='0.7' zIndex='-1' count='140' src="/lib/canvas-nest/canvas-nest-nomobile.min.js"></script>
  <script size="300" alpha="0.1" zIndex="-1" src="/lib/canvas-ribbon/canvas-ribbon.js"></script>
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>




  




  
<script src="/js/local-search.js"></script>









<script>
document.querySelectorAll('.pdfobject-container').forEach(element => {
  let url = element.dataset.target;
  let pdfOpenParams = {
    navpanes : 0,
    toolbar  : 0,
    statusbar: 0,
    pagemode : 'thumbs',
    view     : 'FitH'
  };
  let pdfOpenFragment = '#' + Object.entries(pdfOpenParams).map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join('&');
  let fullURL = `/lib/pdf/web/viewer.html?file=${encodeURIComponent(url)}${pdfOpenFragment}`;

  if (NexT.utils.supportsPDFs()) {
    element.innerHTML = `<embed class="pdfobject" src="${url + pdfOpenFragment}" type="application/pdf" style="height: ${element.dataset.height};">`;
  } else {
    element.innerHTML = `<iframe src="${fullURL}" style="height: ${element.dataset.height};" frameborder="0"></iframe>`;
  }
});
</script>


<script>
if (document.querySelectorAll('pre.mermaid').length) {
  NexT.utils.getScript('//cdn.jsdelivr.net/npm/mermaid@8/dist/mermaid.min.js', () => {
    mermaid.initialize({
      theme    : 'default',
      logLevel : 3,
      flowchart: { curve     : 'linear' },
      gantt    : { axisFormat: '%m/%d/%Y' },
      sequence : { actorMargin: 50 }
    });
  }, window.mermaid);
}
</script>


  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : false,
      appId      : 'uutufTwYVUeCtemIaV78RUzY-gzGzoHsz',
      appKey     : 'EWtCrVS44F22gkjWkQ15x4lx',
      placeholder: "恭迎评论指教（Your comments and criticisms are always welcome.）",
      avatar     : 'mp',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : '' || 'zh-cn',
      path       : location.pathname,
      recordIP   : true,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

</body>
</html>
